<?php
    include 'lib/common/dbRoutines.php';
    include 'lib/dao/WordDao.php';
    header('Content-type: text/html; charset=utf-8');
    
    $level = '';
    
    $file='file.txt';    
    $file_out_name='new_wordsIds.txt';
    
    $conn = getDbConnection();
    $wordDao = new WordDao($conn);
    
    $str = file_get_contents($file);
    
    $tmp  = split("\n",$str);
    $words = array();
    
    foreach($tmp as $k=>$v){
        $v = trim($v);
        if(!empty($v)){
            $words[$v] = 1;
        }
    }
    $words_id = array();
    
    $words_num = count($words);
    $i = 0;
    foreach($words as $k=>$v){
         $lang =  $wordDao -> get_lang($k);
         $i = $i + 1;
         if(!$wordDao -> exists_word($k)){
            if($k!=""){ 
                $sql = "INSERT INTO word_{$lang} (value, complexity, moderated) VALUES (lower('{$k}'), '{$level}', FALSE)";
                mysql_query($sql, $conn) or die (mysql_error());
                $num = mysql_affected_rows();
                if($num==0){
                    echo $k." was not added - error!";
                }else{
                    $sql = "SELECT id FROM word_{$lang} WHERE value='{$k}'";
                    $res = mysql_query($sql, $conn) or die (mysql_error());
                    $words_id[] = mysql_result($res,0);
                   echo $i." word from ".$words_num." done<br>";
               
                  
                }
            }
         }else{
            echo "Was in DB already - {$k}<br>";
         }
    }
    
    $file_out = @fopen ($file_out_name,"r+");
   
    if ( !$file_out ){        
        $file_out = fopen ($file_out_name,"w");
        if ( !$file_out ){
            echo("Ошибка открытия файла");
        }
    }
    else{ 
        fputs ( $file_out, "------------------------------\n");
        foreach($words_id as $k=>$v){
            fputs ( $file_out, $v."\n");
        }
    }
    fclose ($file_out);
    //ob_end_clean ();
?>